package atguigu2.lock;



import java.util.concurrent.locks.ReentrantLock;

/**
 * @AUTHOR LYF
 * @DATE 2022/2/3
 * @VERSION 1.0
 * @DESC
 * 采用synchronized和lock（）实现买票例子
 */
// 第一步,创建资源类，抽象属性及其操作
class Ticket{
    final int SUM = 300;
    private int number = 300;

    public synchronized void sale(){ // 加在方法上，也可加在代码块，或变量上面

        if(number>0){
            System.out.println(Thread.currentThread().getName()+"卖票,已经卖出:"+(SUM-(--number))+"剩余:"+number);
        }

    }
}

//采用 ReentrantLock
class LTicket{
    final int SUM = 300;
    private int number = 300;
    // 可重入锁，默认非公平锁
    private ReentrantLock lock = new ReentrantLock(true);
    public void sale(){
        lock.lock();
        try {
            if(number>0){
                System.out.println(Thread.currentThread().getName()+"卖票,已经卖出:"+(SUM-(--number))+"剩余:"+number);
            }
        }finally {
            lock.unlock();
        }
    }
}

public class SaleTicket {
    //
    //public Ticket ticket = new Ticket();
    // 创建多线程，进行资源类的操作
    public static void main(String[] args) {
        LTicket ticket = new LTicket();
        new Thread(new Runnable() {// Java 8以后可采用lambda
            @Override
            public void run() {
                for(int i=0;i<40;i++){
                    ticket.sale();
                }
            }
        },"Thread-1").start();


        new Thread(()->{
                for(int i=0;i<40;i++){
                    ticket.sale();
                }
        },"Thread-2").start();

        new Thread(()->{
            for(int i=0;i<40;i++){
                ticket.sale();
            }
        },"Thread-3").start();

    }


}
